package com.hqully.smartfumehood.controller;


import com.github.pagehelper.PageInfo;
import com.hqully.smartfumehood.common.utils.PermissionUtil;
import com.hqully.smartfumehood.common.utils.ResultVoUtil;
import com.hqully.smartfumehood.common.vo.QueryVo;
import com.hqully.smartfumehood.common.vo.ResultVo;
import com.hqully.smartfumehood.entity.Device;
import com.hqully.smartfumehood.entity.FumeHood;
import com.hqully.smartfumehood.entity.dto.DeviceDto;
import com.hqully.smartfumehood.service.DeviceService;
import com.hqully.smartfumehood.service.FumeHoodDataService;
import com.hqully.smartfumehood.service.FumeHoodService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lly
 * @since 2022-03-10
 */
@Slf4j
@RestController
@RequestMapping("/api/device")
public class DeviceController extends BaseController{
    @Autowired
    private DeviceService deviceService;

    @Autowired
    private FumeHoodService fumeHoodService;

    @PostMapping("/find-all-device")
    public ResultVo findAllDevice(@RequestHeader("token") String token ,@RequestBody QueryVo queryVo){

        QueryVo realQueryVo = PermissionUtil.setQueryUnitId(token, queryVo);

        PageInfo<DeviceDto> deviceList = deviceService.findAllDevice(realQueryVo);

        return ResultVoUtil.success(deviceList);
    }


    @PostMapping("/find-all-fume-hood")
    public ResultVo findAllFumeHood(@RequestBody QueryVo queryVo){


        PageInfo<FumeHood> allFumeHood = fumeHoodService.findAllFumeHood(queryVo);

        return ResultVoUtil.success(allFumeHood);
    }
    @PostMapping("/find-device-count")
    public ResultVo findDeviceCount(@RequestBody QueryVo queryVo){

        long deviceCount = deviceService.findDeviceCount(queryVo);

        HashMap<String, Long> resultMap = new HashMap<>();
        resultMap.put("deviceCount", deviceCount);

        return ResultVoUtil.success(resultMap);
    }
    
    @PostMapping("/add-device")
    public ResultVo addDevice(@RequestBody Device device){

        try {
            int status = deviceService.addDevice(device);
        } catch (DuplicateKeyException e) {
            return ResultVoUtil.error("该设备号已存在");
        }


        return ResultVoUtil.success("添加设备成功");
    }

    @PostMapping("/delete-device")
    public ResultVo deleteDevice(@RequestBody Device Device){
        deviceService.deleteDevice(Device.getId());

        return ResultVoUtil.success("删除设备成功");
    }

    @PostMapping("/update-device")
    public ResultVo updateDevice(@RequestBody Device device){
        deviceService.updateDevice(device);

        return ResultVoUtil.success("更新设备成功");
    }

}
